/**
 * @description: 实现express内部的path,query,send,sendFile,static方法
 */
const express = require("express");

express.static = function (dirname) {
  return (req, res, next) => {
    let path = require("path");
    let fs = require("fs");
    let absPath = path.join(dirname, req.path);
    fs.stat(absPath, (err, stats) => {
      if (err) return next(err);
      if (stats.isDirectory()) {
        // 如果设置的是目录，读取目录下index
        res.sendFile(absPath + "/index.html");
      } else {
        // 设置的文件，直接把文件读取处理
        res.sendFile(absPath);
      }
    });
  };
};
const app = express();

//  模拟express内部封装的一些方法
app.use(function (req, res, next) {
  const parse = require("parseurl");
  const fs = require("fs");
  const path = require("path");
  const mime = require("mime");
  let { query, path: p } = parse(req);
  req.path = p;
  req.query = query;
  // 实现express的send方法
  res.send = function (value) {
    if (Buffer.isBuffer(value) || typeof value !== "object") {
      res.end(value + "");
    } else if (typeof value === "object") {
      res.end(JSON.stringify(value));
    }
    next();
  };
  // 实现express获取文件sendFile方法
  res.sendFile = function (filename, { root } = {}) {
    let filepath = "";
    if (typeof root === undefined) {
      filepath = path.resolve(filename);
    } else {
      filepath = path.resolve(root, filename);
    }
    res.setHeader("Content-Type", mime.getType(filename) + ";charset=utf-8");
    fs.createReadStream(filepath).pipe(res);
  };
  next();
});
// express.static
app.use(express.static(__dirname));

app.get("/", function (req, res, next) {
  console.log(req.path);
  //   res.send({ ge: 12 });
  res.sendFile("path2Reg.js", { root: __dirname });
});

app.listen(3000);
